package com.zy.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zy.common.Result;
import com.zy.dto.DishDto;
import com.zy.dto.OrdersDto;
import com.zy.entity.*;
import com.zy.service.OrderDetailService;
import com.zy.service.OrdersService;
import com.zy.service.ShoppingCartService;
import com.zy.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 前端控制器
 * </p>
 *
 * @author xyz
 */
@RestController
@Slf4j
@RequestMapping("/order")
@Api(tags = "订单相关接口")
public class OrdersController {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private UserService userService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @ApiOperation(value = "下单接口")
    @PostMapping("/submit")
    public Result<String> submit(HttpServletRequest httpServletRequest,@RequestBody Orders orders){
        //比较繁琐，在service实现
        Long userId = (Long) httpServletRequest.getSession().getAttribute("user");
        orders.setUserId(userId);
        ordersService.submit(orders);
        return Result.success("下单成功");
    }

    @ApiOperation(value = "分页查询订单接口")
    @GetMapping("/page")
    public Result<Page> page(int page, int pageSize, String number,String beginTime,String endTime){
        log.info("开始时间{},结束时间{}",beginTime,endTime);
        //分页构造器,Page(第几页, 查几条)
        Page pageInfo = new Page(page, pageSize);
        //查询构造器
        LambdaQueryWrapper<Orders> lambdaQueryWrapper = new LambdaQueryWrapper();
        //过滤条件.like(什么条件下启用模糊查询，模糊查询字段，被模糊插叙的名称)
        lambdaQueryWrapper.like(!StringUtils.isEmpty(number), Orders::getNumber, number);
        lambdaQueryWrapper.ge(beginTime != null,Orders::getOrderTime,beginTime);
        lambdaQueryWrapper.le(endTime != null,Orders::getOrderTime,endTime);
        //添加排序
        lambdaQueryWrapper.orderByDesc(Orders::getOrderTime);
        //查询分页、自动更新
        ordersService.page(pageInfo, lambdaQueryWrapper);

        List<Orders> records = pageInfo.getRecords();
        List<Orders> list = records.stream().map((item) -> {
            Orders orders = new Orders();
            BeanUtils.copyProperties(item,orders);
            Long userId = item.getUserId();//用户id
            //根据id查询分类对象
            User user = userService.getById(userId);
            if (user != null) {
                String username = user.getName();
                orders.setUserName(username);
            }
            return orders;
        }).collect(Collectors.toList());
        pageInfo.setRecords(list);

        //返回查询结果
        return Result.success(pageInfo);
    }

    @ApiOperation(value = "修改订单状态接口")
    @PutMapping
    public Result<String> updateStatus(@RequestBody Orders orders) {
        ordersService.updateById(orders);
        return Result.success("订单状态修改成功");
    }

    @ApiOperation(value = "分页查询用户订单")
    @GetMapping("/userPage")
    public Result<Page> userPage(HttpServletRequest httpServletRequest,int page,int pageSize) {

        //分页构造器,Page(第几页, 查几条)
        Page pageInfo = new Page(page, pageSize);
        Long userId = (Long) httpServletRequest.getSession().getAttribute("user");
        //查询构造器
        LambdaQueryWrapper<Orders> lambdaQueryWrapper = new LambdaQueryWrapper();
        //过滤条件.like(什么条件下启用模糊查询，模糊查询字段，被模糊插叙的名称)
        lambdaQueryWrapper.like(!StringUtils.isEmpty(userId), Orders::getUserId, userId);
        //添加排序
        lambdaQueryWrapper.orderByDesc(Orders::getOrderTime);
        //查询分页、自动更新
        ordersService.page(pageInfo, lambdaQueryWrapper);
        List<Orders> records = pageInfo.getRecords();
        List<OrdersDto> ordersDtosList = records.stream().map((item) -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item,ordersDto);
            LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper();
            queryWrapper.eq(OrderDetail::getOrderId,item.getId());
            List<OrderDetail> orderDetailList = orderDetailService.list(queryWrapper);
            ordersDto.setOrderDetails(orderDetailList);
            return ordersDto;
        }).collect(Collectors.toList());
        pageInfo.setRecords(ordersDtosList);
        //返回查询结果
        return Result.success(pageInfo);
    }

    @ApiOperation(value = "再来一单")
    @PostMapping("/again")
    public Result<String> submitOrderAgain(HttpServletRequest httpServletRequest,@RequestBody OrdersDto ordersDto) {
        log.info("订单{}",ordersDto);
        LambdaQueryWrapper<OrderDetail> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(!StringUtils.isEmpty(ordersDto),OrderDetail::getOrderId,ordersDto.getId());
        List<OrderDetail> orderDetailList = orderDetailService.list(lambdaQueryWrapper);
        Long userId = (Long) httpServletRequest.getSession().getAttribute("user");

        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(ShoppingCart::getUserId, userId);
        shoppingCartService.remove(queryWrapper);

        // 整体赋值
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map((item) -> {

            // 以下均为赋值操作

            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setUserId(userId);
            shoppingCart.setImage(item.getImage());

            Long dishId = item.getDishId();
            Long setmealId = item.getSetmealId();

            if (dishId != null) {
                // 如果是菜品那就添加菜品的查询条件
                shoppingCart.setDishId(dishId);
            } else {
                // 添加到购物车的是套餐
                shoppingCart.setSetmealId(setmealId);
            }
            shoppingCart.setName(item.getName());
            shoppingCart.setDishFlavor(item.getDishFlavor());
            shoppingCart.setNumber(item.getNumber());
            shoppingCart.setAmount(item.getAmount());
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());
        shoppingCartService.saveBatch(shoppingCartList);
        return Result.success("再次下单成功");
    }
}
